package com.syys.qa.controller;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.BookmarksNavigator;
import com.syys.common.annotation.Log;
import com.syys.common.config.WeCatConfig;
import com.syys.common.core.controller.BaseController;
import com.syys.common.core.domain.AjaxResult;
import com.syys.common.core.page.TableDataInfo;
import com.syys.common.enums.BusinessType;
import com.syys.common.utils.DateUtils;
import com.syys.common.utils.ShiroUtils;
import com.syys.common.utils.StringUtils;
import com.syys.common.utils.file.FileUtils;
import com.syys.common.utils.poi.ExcelUtil;
import com.syys.qa.domain.QaRecord;
import com.syys.qa.domain.QaTheme;
import com.syys.qa.service.IQaRecordService;
import com.syys.qa.service.IQaThemeService;
import com.syys.qa.util.CompressUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * 问卷主题Controller
 *
 * @author ys
 * @date 2021-07-01
 */
@Controller
@RequestMapping("/qa/theme")
public class QaThemeController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(QaThemeController.class);

    private String prefix = "qa/theme";

    @Autowired
    private IQaThemeService qaThemeService;
    @Autowired
    private IQaRecordService qaRecordService;

    @RequiresPermissions("qa:theme:view")
    @GetMapping()
    public String theme() {
        return prefix + "/theme";
    }

    /**
     * 查询问卷主题列表
     */
    @RequiresPermissions("qa:theme:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QaTheme qaTheme) {
        startPage();
        List<QaTheme> list = qaThemeService.selectQaThemeList(qaTheme);
        return getDataTable(list);
    }

    /**
     * 导出问卷主题列表
     */
    @RequiresPermissions("qa:theme:export")
    @Log(title = "问卷主题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(QaTheme qaTheme) {
        List<QaTheme> list = qaThemeService.selectQaThemeList(qaTheme);
        ExcelUtil<QaTheme> util = new ExcelUtil<QaTheme>(QaTheme.class);
        return util.exportExcel(list, "问卷主题数据");
    }

    /**
     * 新增问卷主题
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存问卷主题
     */
    @RequiresPermissions("qa:theme:add")
    @Log(title = "问卷主题", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(QaTheme qaTheme) {
        qaTheme.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(qaThemeService.insertQaTheme(qaTheme));
    }

    /**
     * 修改问卷主题
     */
    @GetMapping("/edit/{themeId}")
    public String edit(@PathVariable("themeId") Long themeId, ModelMap mmap) {
        QaTheme qaTheme = qaThemeService.selectQaThemeById(themeId);
        mmap.put("qaTheme", qaTheme);
        return prefix + "/edit";
    }

    /**
     * 修改保存问卷主题
     */
    @RequiresPermissions("qa:theme:edit")
    @Log(title = "问卷主题", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(QaTheme qaTheme) {
        return toAjax(qaThemeService.updateQaTheme(qaTheme));
    }

    /**
     * 删除问卷主题
     */
    @RequiresPermissions("qa:theme:remove")
    @Log(title = "问卷主题", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(qaThemeService.deleteQaThemeByIds(ids));
    }

    @GetMapping("download")
    public void download(String themeId, HttpServletResponse response) {
        Long themeIdL = Long.valueOf(themeId);
        String date = DateUtils.getDate();
        QaTheme qaTheme = qaThemeService.selectQaThemeById(themeIdL);
        String fileName = qaTheme.getThemeName() + " _" + date;

        QaRecord qaRecord = new QaRecord();
        qaRecord.setThemeId(themeIdL);
        List<QaRecord> qaRecords = qaRecordService.selectQaRecordList(qaRecord);
        if (qaRecords == null || qaRecords.size() == 0) {
            return;
        }
        String saveFilePath = WeCatConfig.getDownloadPath() + "/" + themeId;
        File file = new File(saveFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            File path = new File(ResourceUtils.getURL("classpath:people.docx").getPath());
            Document doc = new Document(path.getPath());
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
            qaRecords.forEach(qaRecordDB -> {
                String[] fields = new String[]{"name", "age", "sex", "remark"};
                bookmarkNavigator.moveToBookmark("themeName");
                //使用文本替换原书签的内容, false表示不保留原来的格式
                bookmarkNavigator.replaceBookmarkContent(qaTheme.getThemeName(), true);

                bookmarkNavigator.moveToBookmark("name");
                bookmarkNavigator.replaceBookmarkContent(qaRecordDB.getName(), true);

                bookmarkNavigator.moveToBookmark("age");
                bookmarkNavigator.replaceBookmarkContent(qaRecordDB.getAge(), true);

                bookmarkNavigator.moveToBookmark("sex");
                bookmarkNavigator.replaceBookmarkContent(qaRecordDB.getSex(), true);

                bookmarkNavigator.moveToBookmark("remark");
                bookmarkNavigator.replaceBookmarkContent(qaRecordDB.getRemark(), true);
                //            Arrays.stream(fields).forEach(field -> {
                //                bookmarkNavigator.moveToBookmark(field);
                //                //使用文本替换原书签的内容, false表示不保留原来的格式
                //                bookmarkNavigator.replaceBookmarkContent(StringUtils.defaultIfBlank(ReflectUtils.invokeGetter(QaRecord.class, field), ""), true);
                //            });

                //保存文档
                doc.saveToFile(saveFilePath + "/" + qaRecordDB.getName() + "_" + qaRecordDB.getRecordId() + ".docx", FileFormat.Docx);
            });
            CompressUtil.zipFile(file, "zip");
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileUtils.deleteFile(saveFilePath);
        fileName = file.getPath() + ".zip";
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
//            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, qaTheme.getThemeName() + " _" + date + ".zip");
            FileUtils.writeBytes(filePath, response.getOutputStream());
            FileUtils.deleteFile(filePath);
        } catch (Exception e) {
            LOGGER.error("下载文件失败", e);
        }
    }

}
